package com.framework.loippi.controller;

import com.framework.loippi.utils.ReturnJson;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by longbh on 16/7/28.
 */
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public static final String[] ignoreExceptionMessages = new String[]{
            "你的主机中的软件中止了一个已建立的连接。",
            "Broken pipe",
            "断开的管道",
            "Your request params is invalid. Please check them according to error message."
    };

    public boolean ignoreExcepionMessage(String message) {
        for (String iem : ignoreExceptionMessages) {
            if (message.contains(iem))
                return true;
        }
        return false;
    }

    @ExceptionHandler({StateResult.class})
    @ResponseBody()
    public String Exception(StateResult e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", e.code);
        String message = e.message;
        map.put("message", message);
        map.put("data", e.data);
        JSONObject json = JSONObject.fromObject(map);

        if(ignoreExcepionMessage(message)){
            logger.warn("系统错误[" + request.getRequestURI() + "]", e);
        }else{
            logger.error("系统错误[" + request.getRequestURI() + "]", e);
        }

        return json.toString();
    }

    protected String jsonSucess() {
        return ReturnJson.jsonString("成功", 2000000);
    }

    protected String jsonSucess(Object data) {
        return ReturnJson.jsonString("成功", data, 2000000);
    }

    protected String jsonFail() {
        return ReturnJson.jsonString("失败", 5000000);
    }

    protected String jsonFail(int status) {
        return ReturnJson.jsonString("失败", status);
    }

    protected String jsonFail(int status, String message) {
        return ReturnJson.jsonString(message, status);
    }

}
